# =============================================================================
#'
#' @title Write Time Series
#'
#' @description Write GEOtop time series
#'
#' @details This function writes a GEOtop time series such as a meteo file or 
#' a result file. Data is sorted ascending by the "Date" column.
#'
#' @param data Data frame that contains the data to be written as a time series.
#' it must contain a column of type POSIXct named "Date". All other columns 
#' must be of type numeric.
#' @param outfile Full path to the file that should be written.
#' @param round Optional rounding applied to all columns. This can be 0-6 digits
#' with the default of -1 indicating no rounding.
#' @param comment Optional comment to be included in the beginning lines of file.
#' @param env List that passes a number of default settings.
#' @export
#' @examples
#' TimeSeriesWrite(meteo, "./data/meteo0001.txt")
#'
#' @author Stephan Gruber <stephan.gruber@@carleton.ca>
#'
# =============================================================================
TimeSeriesWrite <- function(data, outfile, round = -1, 
                            comment = "", env = SetEnv()) {
  #test for correct Date
  if (class(data$Date)[1] != "POSIXct") {
  	stop("Column named 'Date' in POSIXct time format is missing.")
  }                  
  data <- data[with(data, order(Date)), ]          #sort by Date
  Date <- format(data$Date, format = env$timefmt)  #make date string
  data <- subset(data, select = -Date)
      	
  if ((sum(sapply(data, class) != "numeric") > 0)) {
  	stop("One or more columns of input data frame are of non-numeric type.")
  }  
                            	                            
  if (round >= 0) {
  	if (round > 6) break
    data <- round(data, round)  
  }
  
  data <- cbind(Date, data) #recombine data and Date

  #write comment
  append <- FALSE
  if (comment != "") {
    con <- file(outfile, "w")
    cat(env$comchar, comment, '\n', file = con, sep="")	
    close(con)
  	append <- TRUE
  }


  #write data
  write.table(data, file = outfile, append = append, quote = FALSE, sep = ",",
              eol = "\n", na = "NA", dec = ".", row.names = FALSE,
              col.names = TRUE)
}	

